package cn.zniot.so.transport.server;

import cn.zniot.so.transport.IServer;
import cn.zniot.so.transport.exception.NetException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 默认TCP/UDP服务器接口适配器
 */
public class ServerAdapter extends IoHandlerAdapter implements IServer {
	private static final Log logger = LogFactory.getLog(ServerAdapter.class);
	// 默认连接池
	protected ThreadPoolExecutor threadPool = null;
	// 当前监听器
	protected NioSocketAcceptor acceptor = null;
	// 协议转换工厂类
	protected ProtocolCodecFactory factory = null;
	// 逻辑处理器类
	protected IoHandler handler = null;

	@Override
	public void setHandler(IoHandler handler) {
		this.handler = handler;
	}

	@Override
	public void setProtocolCodec(ProtocolCodecFactory factory) {
		this.factory = factory;
	}

	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("messageReceived... Please provide logic handler.");
		}
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("sessionClosed... Please provide logic handler.");
		}
//		session.close(true);
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("sessionCreated... Please provide logic handler.");
		}
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("sessionIdle... Please provide logic handler.");
		}
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("sessionOpened... Please provide logic handler.");
		}
	}
	
	@Override
	public void shutdown() throws NetException  {
		this.acceptor.unbind();
		this.acceptor.dispose();
		this.threadPool.shutdown();
		try
		{
			this.threadPool.awaitTermination(1, TimeUnit.SECONDS);
		} catch (InterruptedException e)
		{
			logger.error(e);
		}
		this.threadPool.shutdownNow();
		if (logger.isDebugEnabled()) {
			logger.debug("TCP Server has been stoped...");
		}
	}
	
	@Override
	public void startup() throws NetException {

	}

	@Override
	public void init() {

	}
	
	@Override
	public String getStatus() {
		return null;
	}

}
